package com.skyline.energy.provider.skyline;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.skyline.energy.dataaccess.jdbc.KeyHolder;
import com.skyline.energy.exception.DataAccessException;
import com.skyline.energy.utils.JdbcUtils;

class UpdateCallback implements PreparedStatementCallback<Integer> {
	private static final Log LOGGER = LogFactory.getLog(UpdateCallback.class);

	private final KeyHolder generatedKeyHolder;

	public UpdateCallback(KeyHolder generatedKeyHolder) {
		this.generatedKeyHolder = generatedKeyHolder;
	}

	@Override
	public Integer doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
		int rows = ps.executeUpdate();

		if (generatedKeyHolder != null) {
			List<Map<String, Object>> generatedKeys = generatedKeyHolder.getKeyList();
			generatedKeys.clear();
			ResultSet keys = ps.getGeneratedKeys();
			if (keys != null) {
				try {
					RowMapperResultSetExtractor<Map<String, Object>> rse = new RowMapperResultSetExtractor<Map<String, Object>>(
							new ColumnMapRowMapper(), 1);
					generatedKeys.addAll(rse.extractData(keys));
				} finally {
					JdbcUtils.closeResultSet(keys);
				}
			}
			if (LOGGER.isDebugEnabled()) {
				LOGGER.debug("SQL update affected " + rows + " rows and returned " + generatedKeys.size() + " keys");
			}
		}

		return rows;
	}

}
